package cn.jly.spring.boot.cloud.controller;

import cn.jly.spring.boot.cloud.beans.User;
import cn.jly.spring.boot.cloud.dao.UserRepository;
import cn.jly.spring.boot.cloud.exception.DataBindingException;
import cn.jly.spring.boot.cloud.service.UserService;
import cn.jly.spring.boot.cloud.utils.DataValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lanyangji
 * @description
 * @date 2020/11/25 下午 3:52
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @DeleteMapping("/user")
    public List<User> deleteByLastNameContains(String lastName) {
        return userService.deleteAllByUsernameContains(lastName);
    }

    @GetMapping("/users")
    public Page<User> findUsers(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    @PostMapping(value = "/user", consumes = {MediaType.APPLICATION_JSON_VALUE})
    public User saveUser(@RequestBody @Validated User user, BindingResult result) {
        if (result.hasErrors()) {
            throw new DataBindingException(DataValidateUtil.validate(result));
        }

        return userRepository.save(user);
    }
}
